package cn.huhst.cas.weisiqian.service;

import java.util.ArrayList;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.dao.DuplicateEntryException;
import cn.huhst.cas.weisiqian.dao.UserDao;
import cn.huhst.cas.weisiqian.pojo.User;

public class UserService {

	private UserDao userdao = null;
	private Logger logger = Logger.getLogger(UserService.class);

	public UserService() {
		userdao = new UserDao();
	}

	public User isExistNameAndPassword(String username, String userpassword) {
		User user = userdao.searchByNameAndPassword(username, userpassword);
		return user;
	}

	public boolean addUser(User user) throws UserExistException {
		int count;
		try {
			count = userdao.addUser(user);
		} catch (DuplicateEntryException e) {
			logger.error("用户已存在", e);
			throw new UserExistException("用户已存在");
		}
		if (count > 0) {
			logger.info("添加用户成功");
			return true;
		} else {
			logger.info("添加用户失败");
			return false;
		}
	}

	public ArrayList<User> AllUsers() {
		return userdao.queryAll();
	}

	/**
	 * 分页查询
	 * @param pageIndex 页码
	 * @param pageSize 分页大小
	 * @return
	 */
	public ArrayList<User> getUsers(int pageIndex, int pageSize) {
		int index = (pageIndex - 1) * pageSize;
		return userdao.limit(index, pageSize);
	}
	
	/**
	 * 分页查询,默认分页大小为10
	 * @param pageIndex 页码
	 * @return
	 */
	public ArrayList<User> getUsers(int pageIndex) {
		int pageSize = 10;
		int index = (pageIndex - 1) * pageSize;
		return userdao.limit(index, pageSize);
	}

	public int getCount() {
		return userdao.getCount();
	}

	public boolean deleteUser(String username) {
		boolean result = userdao.deleteUserByUsername(username);
		return result;
	}

	public boolean updateUser(User user) {
		boolean result = userdao.updateUser(user);
		return result;
	}
}
